import sys
from pathlib import Path
import json
from typing import Optional

sys.path.append(str(Path(__file__).parent.parent.parent))
from reqapi.api import BaseApi, ApiConfig
from model.sms_code_models import SendSignInSmsCodeRequest, SendSignInSmsCodeResponse


class AuthSmsCodeApi(BaseApi):
    """认证短信验证码API"""
    
    def send_sign_in_sms_code(self, mobile: str, code: str = "", area: str = "86", raise_on_error: bool = False) -> Optional[SendSignInSmsCodeResponse]:
        """发送登录短信验证码，日志风格与统一API一致，异常和错误码时返回None"""
        endpoint = "/api/user/Auth/SendSignInSmsCode"
        url = f"{self.BASE_URL}{endpoint}"
        request = SendSignInSmsCodeRequest(
            Area=area,
            Mobile=mobile,
            Code=code,
            Sessionid=self.device_id or ""
        )
        request_data = {
            "Area": request.Area,
            "Code": request.Code,
            "Mobile": request.Mobile,
            "Sessionid": request.Sessionid
        }
        headers = self.common_headers.copy()
        headers["apptype"] = "4"
        headers["authorization"] = "Bearer"
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            if resp_json.get('code', 0) != 0 and resp_json.get('Code', 0) != 0:
                print(f"API返回错误: {resp_json.get('msg', resp_json.get('Msg', '未知错误'))}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('msg', resp_json.get('Msg'))}")
                return None
            # 修正返回对象，始终用from_dict保证Data字段为对象
            if 'Code' in resp_json:
                # 已是大写风格，直接from_dict
                return SendSignInSmsCodeResponse.from_dict(resp_json)
            # 兼容小写风格（如code/msg/data）
            resp_json_fixed = {
                'Code': resp_json.get('code', 0),
                'Msg': resp_json.get('msg', ''),
                'TipType': resp_json.get('tipType', 0),
                'Data': resp_json.get('data', {})
            }
            return SendSignInSmsCodeResponse.from_dict(resp_json_fixed)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None


def main():
    """测试发送登录短信验证码API"""
    try:
        device_id = "Z+Z/Uj4xyKoDAJp249r21qHx"
        mobile = "15999957262"  # 示例手机号
        api = AuthSmsCodeApi(
            device_token=device_id,
            device_id=device_id,
            auth_token="Bearer",  # 根据请求示例设置
            uk="5FGaLrLar6b7EWUnNmqNpKGjU88E7TrsHnqsWlwo9ncsogqazR1hLGldi30biVJ1N"  # 示例UK值
        )
        response = api.send_sign_in_sms_code(mobile)
        print("\n=== 发送登录短信验证码结果 ===")
        if response is None:
            print("短信验证码发送失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"状态码: {response.Code}")
            print(f"消息: {response.Msg}")
            print(f"提示类型: {response.TipType}")
            if isinstance(response.Data, dict):
                secs = response.Data.get('Secs')
                img_url = response.Data.get('ImgVerifyUrl')
                mobile = response.Data.get('Mobile')
            else:
                secs = getattr(response.Data, 'Secs', None)
                img_url = getattr(response.Data, 'ImgVerifyUrl', None)
                mobile = getattr(response.Data, 'Mobile', None)
            print(f"验证码有效期: {secs}秒")
            print(f"图片验证码URL: {img_url}")
            print(f"手机号: {mobile}")
        return response.Data if response else False
    except Exception as e:
        print(f"短信验证码发送失败: {e}")
        return False


if __name__ == "__main__":
    main()
